package com.xinz.config;

import java.io.Reader;
import java.util.Properties;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 资源库初始化操作
 *
 */
public class MapperManager {

	private static final Logger log = LoggerFactory.getLogger(MapperManager.class);
	private static final String SQL_MAPPER_CONFIG_FILE = "com/xinz/config/maps/MapperConfig.xml";
	private static final String DB_URL = "url";
	private static final String DB_PASSWORD = "password";
	private static final String DB_USERNAME = "username";
	private static final String DB_DRIVER = "driver";
	
	private static SqlSessionFactory sqlMapperConfig;
	
	/**
	 * 初始化数据库连接
	 */
	public static void init() {
		try {
			Reader reader = Resources.getResourceAsReader(SQL_MAPPER_CONFIG_FILE);
			
			Properties props = new Properties();
			
			Element res = GlobalConfig.getRes();
			
			props.setProperty(DB_DRIVER, res.attributeValue(DB_DRIVER));
			props.setProperty(DB_USERNAME, res.attributeValue(DB_USERNAME));
			props.setProperty(DB_PASSWORD, res.attributeValue(DB_PASSWORD));
			props.setProperty(DB_URL, res.attributeValue(DB_URL));
			
			sqlMapperConfig = new SqlSessionFactoryBuilder().build(reader, props);
		}
		catch(Exception e) {
			log.error("init mysql error:" + e);
		}
	}
	
	public static SqlSessionFactory getResSqlMapper() {
		return sqlMapperConfig;
	}
}
